package com.weme.common.activity

import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.text.TextUtils
import android.util.Log
import androidx.activity.result.ActivityResultLauncher
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentActivity
import androidx.viewpager2.adapter.FragmentStateAdapter
import androidx.viewpager2.widget.ViewPager2
import com.gyf.immersionbar.BarHide
import com.gyf.immersionbar.ImmersionBar
import com.jeremyliao.liveeventbus.LiveEventBus
import com.weme.chat.bean.GiftMessage
import com.weme.chat.bean.toMap
import com.weme.common.R
import com.weme.common.base.BaseMvvmActivity
import com.weme.common.databinding.ActivityLookBigImgBinding
import com.weme.common.dialog.DialogUtils
import com.weme.common.dialog.GiftDialog
import com.weme.common.dialog.GiftDialogCallback
import com.weme.common.dialog.GiftSendSuccessDialog
import com.weme.common.fragment.LookBigImgFragment
import com.weme.common.util.*
import com.weme.common.util.LiveConfig.NET_WORK_USER_LOOK_ALBUM
import com.weme.common.view.BottomSelectionListener
import com.weme.common.view.CustomDialogFragment
import com.weme.common.view.CustomTopNavigationBarListener
import com.weme.common.viewmodel.LookBigImgViewMode
import dev.kratos.api.user_server.v1.*
import io.agora.CallBack
import io.agora.chat.ChatClient
import io.agora.chat.ChatMessage
import io.agora.chat.CustomMessageBody

class LookBigImgActivity : BaseMvvmActivity<ActivityLookBigImgBinding, LookBigImgViewMode>(), BottomSelectionListener {

    val fragment = mutableListOf<Fragment>()
    var oldPosition = 0
    var userId = 0L
   var albumList= mutableListOf<Media>()

    companion object {
        private const val EXTRA_USER = "Users"
        private const val EXTRA_POSITION = "position"



        fun openActivity(activity: FragmentActivity, dataBean: Users, position: Int = 0, resultLauncher: ActivityResultLauncher<Intent>) {
            val intent = Intent(activity, LookBigImgActivity::class.java)
            intent.putExtra(EXTRA_USER, dataBean)
            intent.putExtra(EXTRA_POSITION, position)


            resultLauncher.launch(intent)
        }
    }

    var giftDialog: GiftDialog? = null
    override fun initView(savedInstanceState: Bundle?) {
        ImmersionBar.with(this).hideBar(BarHide.FLAG_HIDE_NAVIGATION_BAR).titleBar(mBinding.customTopNavigationBar).init()
        mBinding.svgaGift.playSVGAFromAssets("gift_button_animation")
        mBinding.calCall.playSVGAFromAssets("video_preview_call_her")

        val intent = intent
        val users = intent.getSerializableExtra(EXTRA_USER) as Users
        val position = intent.getIntExtra(EXTRA_POSITION, 0)
        val isMe =   UserMKHelper.decodeLong(UserMKHelper.UID) == users.uid
        LiveEventBus.get<Any>(NET_WORK_USER_LOOK_ALBUM).observe(this){
            if(it is SendGiftReply){
                if (TextUtils.isEmpty(it.gift.giftUrl)) {
                    val giftSendSuccessDialog = GiftSendSuccessDialog(users.nickname,users.headPic)
                    giftSendSuccessDialog.show(this@LookBigImgActivity.supportFragmentManager, "GiftSendSuccessDialog")
                } else {
                    mBinding.playerView.loadVideoFromAssets(it.gift.giftName + ".mp4", it.gift.md5){
                        downloadMp4(it.gift.giftUrl,it.gift.giftName){ isDow->
                            if(isDow == true){
                                mBinding.playerView.loadVideoFromAssets(it.gift.giftName + ".mp4", it.gift.md5){

                                }
                            }

                        }
                    }
                }
                AgoraClient.sendImGiftMsg(userId.toString(),it.gift)
            } else  if (it is ReportReply) { //举报回调
                showToast(getString(com.example.resources.R.string.report_successful))
            }

        }

        userId =users.uid
        
        mBinding.customTopNavigationBar.getMore().setImageResource(if(isMe) com.example.resources.R.drawable.icon_user_del else com.example.resources.R.mipmap.icon_look_report)
        mBinding.imGift.setVisible(!isMe)
        mBinding.calCall.setVisible(!isMe)
        mBinding.imGift.setOnClickListener {
            if (null == giftDialog) {
                giftDialog = GiftDialog(users.nickname, object : GiftDialogCallback {
                    override fun sendGiftInfo(giftInfo: GiftInfo) {
                        viewModel.sendGift(SendGiftRequest.newBuilder().setGiftId(giftInfo.id).setGiftNum(1).setUid(userId).build())
                        giftDialog?.dismiss()
                    }
                })
            }

            giftDialog?.show(this.supportFragmentManager, "")
        }
        mBinding.calCall.setOnClickListener {

            if (isVip()) {
                viewModel.callsPhone(users)
            } else {
                showToast("跳转到订阅商城")
            }

            //                val toCallActivity = Intent(this@LookBigImgActivity, CallActivity::class.java)
            //                val options = ActivityOptions.makeCustomAnimation(this@LookBigImgActivity, com.weme.common.R.anim.fade_in, com.weme.common.R.anim.fade_out)
            //                startActivity(toCallActivity, options.toBundle())
        }

        albumList.addAll(users.mediaList)

        users.mediaList.forEach {
            val lookBigImgFragment = LookBigImgFragment.newInstance(it.type, it.url, isMe)
            fragment.add(lookBigImgFragment)
        }
        mBinding.vp2.adapter = object : FragmentStateAdapter(this) {
            override fun getItemCount(): Int {
                return fragment.size
            }

            override fun createFragment(p0: Int): Fragment {
                return fragment[p0]
            }
        }

        mBinding.magical.attachViewPager(mBinding.vp2, users.mediaList.size)
        mBinding.vp2.setCurrentItem(position, false)
        oldPosition = position
        mBinding.vp2.registerOnPageChangeCallback(object : ViewPager2.OnPageChangeCallback() {
            override fun onPageScrollStateChanged(state: Int) {
                super.onPageScrollStateChanged(state)


            }

            override fun onPageSelected(position: Int) {
                super.onPageSelected(position)
                if (fragment.size < oldPosition) {
                    (fragment[oldPosition] as LookBigImgFragment).onPlayerStop()
                }

                (fragment[position] as LookBigImgFragment).onPlayerPlay()
                oldPosition = position

            }
        })


        mBinding.customTopNavigationBar.listener = object : CustomTopNavigationBarListener {
            override fun onMoreButtonClicked() {
                if(isMe){
                    val dialog = CustomDialogFragment.newInstance(title = getString(com.example.resources.R.string.delete), content = getString(com.example.resources.R.string.dialog_out_content), positiveButtonText = getString(com.example.resources.R.string.cancel), negativeButtonText = getString(com.example.resources.R.string.yes), listener = object : CustomDialogFragment.DialogClickListener {
                        override fun onPositiveButtonClick() {
                        }

                        override fun onNegativeButtonClick() {
                            delImg()

                        }
                    })
                    dialog.show(supportFragmentManager, "CustomDialog")  
                }else{
                    DialogUtils.createAndShowBottomSelectionDialog(this@LookBigImgActivity, getString(
                        com.example.resources.R.string.report), this@LookBigImgActivity)
                }
              
            } //     }

        }


    }

    fun delImg( ) {
        val current = mBinding.vp2.currentItem
        if (albumList.size >= current) {
            val data = albumList[current]
            val media = Media.newBuilder().setType(data.type).setUrl(data.url).setId(data.id).build()
            viewModel.delAlbumApi(DeleteAlbumRequest.newBuilder().addMedia(media).build())
            albumList.removeAt(current)

            fragment.removeAt(current) // mBinding.vp2.adapter?.notifyItemRemoved(current)
            shuaxin(albumList.size)
            mBinding.magical.invalidate()
            if (fragment.size == 0) {
                val resultIntent = Intent()
                setResult(Activity.RESULT_OK, resultIntent)
                finish()

            }
        }
    }

    fun shuaxin(size: Int) {
        mBinding.vp2.adapter = object : FragmentStateAdapter(this) {
            override fun getItemCount(): Int {
                return fragment.size
            }

            override fun createFragment(p0: Int): Fragment {
                return fragment[p0]
            }
        }

        mBinding.magical.attachViewPager(mBinding.vp2, size)
    }


    override fun onDestroy() {
        super.onDestroy() // 释放播放器资源
        mBinding.svgaGift.stopAnimation()
        mBinding.svgaGift.clear()
        mBinding.playerView.stopPlay()
        mBinding.playerView.release()
        mBinding.calCall.stopAnimation()
        mBinding.calCall.clear()

    }

    override fun getViewModelClass(): Class<LookBigImgViewMode> = LookBigImgViewMode::class.java
    override fun onTitleClicked(position: Int) {
        when (position) {
            0 -> {
                viewModel.setReport(ReportRequest.newBuilder().setReportUid(userId).setReportContent(getString(com.example.resources.R.string.report_1)).build())
            }
            1 -> {
                viewModel.setReport(ReportRequest.newBuilder().setReportUid(userId).setReportContent(getString(com.example.resources.R.string.report_2)).build())
            }
            2 -> {
                viewModel.setReport(ReportRequest.newBuilder().setReportUid(userId).setReportContent(getString(com.example.resources.R.string.report_3)).build())
            }
            3 -> {
                viewModel.setReport(ReportRequest.newBuilder().setReportUid(userId).setReportContent(getString(com.example.resources.R.string.report_4)).build())
            }
            4 -> {
                viewModel.setReport(ReportRequest.newBuilder().setReportUid(userId).setReportContent(getString(com.example.resources.R.string.report_5)).build())
            }
            5 -> {
                viewModel.setReport(ReportRequest.newBuilder().setReportUid(userId).setReportContent(getString(com.example.resources.R.string.report_6)).build())
            }
            6 -> {
                viewModel.setReport(ReportRequest.newBuilder().setReportUid(userId).setReportContent(getString(com.example.resources.R.string.report_7)).build())
            }
        }
    }


}